let cached = null;

export async function getConfig() {
  if (cached) return cached;
  try {
    const res = await fetch('/config.json', { cache: 'no-store' });
    if (!res.ok) throw new Error('Failed to load config');
    cached = await res.json();
  } catch (e) {
    cached = {
      API_BASE: 'http://127.0.0.1:8000',
      // 前端跳转域名（用于支付回跳等场景）
      RETURN_BASE: 'http://429b035d.r28.cpolar.top/'
    };
  }
  return cached;
}

export async function getApiBase() {
  const cfg = await getConfig();
  const base = (cfg.API_BASE || 'http://127.0.0.1:8000').replace(/\/+$/, '');
  return base;
}

export async function makeUrl(path) {
  const base = await getApiBase();
  const clean = String(path || '').replace(/^\/+/, '');
  return `${base}/${clean}`;
}

// 获取前端跳转域名
export async function getReturnBase() {
  const cfg = await getConfig();
  const base = (cfg.RETURN_BASE || 'http://429b035d.r28.cpolar.top/').replace(/\/+$/, '');
  return base;
}

// 生成前端跳转完整链接
export async function makeReturnUrl(path) {
  const base = await getReturnBase();
  const clean = String(path || '').replace(/^\/+/, '');
  return `${base}/${clean}`;
}